package cn.edu.zut.sunday.boolq.controller;


import cn.edu.zut.sunday.base.controller.GenericController;
import cn.edu.zut.sunday.boolq.domain.BoolqInfo;
import cn.edu.zut.sunday.boolq.service.BoolqInfoService;
import cn.edu.zut.sunday.boolq.vo.BoolqInfoQuery;
import com.google.common.collect.Lists;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import io.swagger.annotations.Api;
import java.util.ArrayList;
import javax.persistence.criteria.Predicate;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@Slf4j
@Api("boolq-数据集实体表接口")
@RestController
@CrossOrigin
@RequestMapping("/boolq/boolqInfo")
public class BoolqInfoController extends GenericController<BoolqInfo,Integer, BoolqInfoService> {
    /**
     * 创建boolqInfoService对象
     * @param boolqInfoService  由IOC自动注入服务对象
     */
    @Autowired
    public void setBoolqInfoService(BoolqInfoService boolqInfoService){
        this.service = boolqInfoService;
    }

    /**
     * 对前端传送的高级搜索进行配置，主要根据（question, title）属性进行高级搜索
     *
     * @param requestBodyStr 请求的RequestBody字符串对象，需要之类使用序列化工具创建对应对象
     * @return 返回Specification对象
     */
    @Override
    protected Specification<BoolqInfo> createSpecification(String requestBodyStr) {
        try {
            final BoolqInfoQuery infoQuery = new Gson().fromJson(requestBodyStr,
              BoolqInfoQuery.class);
            final ArrayList<Predicate> list = Lists.newArrayList();

            return (root, query, cb) -> {
                if (StringUtils.isNotEmpty(infoQuery.getQuestion())) {
                    list.add(cb.like(root.get("question"), sqlLike(infoQuery.getQuestion())));
                }
                if (StringUtils.isNotEmpty(infoQuery.getTitle())) {
                    list.add(cb.like(root.get("title"),sqlLike(infoQuery.getTitle()) ));
                }
                return cb.and(list.toArray(new Predicate[0]));
            };
        } catch (JsonSyntaxException e) {
            log.error("反序列化对象失败: {}", requestBodyStr);
        }
        return null;
    }
}
